package com.gydz.interferencenetworkmanagement.common.netty.server;

import com.gydz.interferencenetworkmanagement.common.netty.handler.NettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.springframework.stereotype.Component;


@Component
public class TcpNettyServer {

    public static void main(String[] args) {
        TcpNettyServer tcpNettyServer = new TcpNettyServer();
        tcpNettyServer.run(8000);
    }

    public void run(int port) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        System.out.println("准备运行端口：" + port);
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)     //配置现场模型
                .channel(NioServerSocketChannel.class)      //配置IO模型
                .childHandler(new ChannelInitializer<NioSocketChannel>() {  //配置处理
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) {
                        nioSocketChannel.pipeline().addLast(new NettyServerHandler());
                    }
                });
        bind(bootstrap, port);

    }

    //实现绑定重新绑定方法
    private void bind(final ServerBootstrap bootstrap, final int port) {
        bootstrap.bind(port).addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                if (future.isSuccess()) {
                    System.out.println("端口绑定成功");
                } else {
                    System.out.println(port + "端口绑定失败,重新绑定" + port + 1);
                    bind(bootstrap, port + 1);
                }
            }
        });
    }
}
